<?php
namespace frontend\controllers;

use common\models\Catalog;
use common\models\Meta;
use common\models\Post;
use common\models\PostAttr;
use common\utils\XCache;
use common\utils\XMap;
use Yii;

/**
 * 内容控制器
 */
class PostController extends BaseController
{
    public function actionIndex($id)
    {
        //$model = Post::findOne($id);
        $model = XCache::post($id);
        if (!$model) {
            $this->tips('该内容已经不存在');
        }
        $model->viewUpdate($id);
        if ($model->is_link == 1) {
            //外链
            $this->redirect($model->link, 301);
        } else {
            //$catalog = Catalog::findOne($model->catalog_id);
            $catalog = XCache::catalogById($model->catalog_id);
            if (!$catalog) {
                $this->tips('该栏目已经不存在');
            }
            Yii::$app->view->params['alias'] =$catalog->alias ;
            $view_show = $catalog->view_show;
            if ($model->view_show) {
                $view_show = $model->view_show;
            }
            $this->layout = XMap::layoutPost($view_show);

            //上一条
            $queryPrev = Post::find();
            $queryNext = Post::find();
            //获取$catalogId子类
            $childIdes = $catalog->getChildIdes($catalog->id);
            if ($childIdes) {
                $ids = $catalog->id . ',' . $childIdes;
                $queryPrev->where("catalog_id in($ids)");
                $queryNext->where("catalog_id in($ids)");
            } else {
                $queryPrev->where("catalog_id=$catalog->id");
                $queryNext->where("catalog_id=$catalog->id");
            }
            $prev = $queryPrev->andWhere("id<$id")->orderBy("id desc")->asArray()->one();
            //下一条
            $next = $queryNext->andWhere("id>$id")->orderBy("id asc")->asArray()->one();

            $meta = Meta::get($model->tableName(), $model->id);
            if ($meta->id) {
                $this->view->title = $meta->title;
                $this->setSeo($meta->keywords, $meta->description);
            } else {
                $this->view->title = $model->title;
            }

            //属性
            $attributesList = PostAttr::find()->select("name,val")->where("post_id=:post_id", [":post_id" => $id])->all();
            $attributes = [];
            foreach ((array)$attributesList as $item) {
                $attributes[$item['name']] = $item['val'];
            }

            return $this->xrender($view_show, [
                'catalog' => $catalog,
                'post' => $model,
                'prev' => $prev,
                'next' => $next,
                'attributes' => $attributes,
            ]);
        }
    }
}
